package com.fastjpa.controller;

import com.efeichong.dynamic.DS;
import com.efeichong.dynamic.DynamicDataSource;
import com.efeichong.dynamic.DynamicDataSourceContextHolder;
import com.fastjpa.ResponseData;
import com.fastjpa.dao.ClazzDao;
import com.fastjpa.entity.Clazz;
import com.fastjpa.service.impl.Test;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lxk
 * @date 2022/9/1
 * @description
 */
@RestController
@RequestMapping("dynamic")
@RequiredArgsConstructor
public class DynamicController {

    private final ClazzDao clazzDao;
    private final Test test;

    @DS("slave1")
    @GetMapping("get")
    public void get(){
        List<Clazz> clazzes = clazzDao.selectAll();
        System.out.println(clazzes.stream().map(Clazz::getName).collect(Collectors.joining()));
    }

    @GetMapping("get0")
    public void get0(){
        List<Clazz> clazzes = clazzDao.selectAll();
        System.out.println(clazzes.stream().map(Clazz::getName).collect(Collectors.joining()));
    }

    @GetMapping("get2")
    public void get2(){
        DynamicDataSourceContextHolder.push("master");
        List<Clazz> master = clazzDao.selectAll();
        System.out.println(master.stream().map(Clazz::getName).collect(Collectors.joining()));

        DynamicDataSourceContextHolder.push("slave1");
        List<Clazz> slave1 = clazzDao.selectAll();
        System.out.println(slave1.stream().map(Clazz::getName).collect(Collectors.joining()));

        DynamicDataSourceContextHolder.push("slave2");
        List<Clazz> slave2 = clazzDao.selectAll();
        System.out.println(slave2.stream().map(Clazz::getName).collect(Collectors.joining()));
    }

    @Transactional
    @GetMapping("get3")
    public void get3(){
        List<Clazz> master = test.getMaster();
        System.out.println(master.stream().map(Clazz::getName).collect(Collectors.joining()));

        List<Clazz> slave1 = test.getSlave1();
        System.out.println(slave1.stream().map(Clazz::getName).collect(Collectors.joining()));

        List<Clazz> slave2 = test.getSlave2();
        System.out.println(slave2.stream().map(Clazz::getName).collect(Collectors.joining()));
    }

    @Transactional
    @GetMapping("save")
    public void save(){
        test.saveMaster();
        test.saveSlave1();
        test.saveSlave2();
    }

}
